<template>
  <div class="peer">
    <video autoPlay playsInline muted :controls="false" :ref="`video_peer_${this.peerId}`"></video>
    <audio autoPlay muted :controls="false" :ref="`audio_peer_${this.peerId}`"></audio>
  </div>
</template>

<script>
export default {
  name: "peer",
  data() {
    return {}
  },
  props: {
    peerId: [String, Number],
    peerData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  watch: {
    "$store.state.consumers": {
      handler(nval, oval) {
        let arr = nval[this.peerId]
        if (Array.isArray(arr) && arr.length === 2) {
          this.handleSetTrack(arr)
        }
      },
      deep: true
    }
  },
  methods: {
    handleSetTrack(arr) {
      let videoEl = this.$refs[`video_peer_${this.peerId}`]
      let audioEl = this.$refs[`audio_peer_${this.peerId}`]
      let videoTrack, audioTrack
      arr.forEach((item) => {
        let track = item.track
        let type = track.kind
        switch (type) {
          case 'video':
            videoTrack = track
            break
          case 'audio':
            audioTrack = track
            break
        }
      })
      let videoStream = new MediaStream
      let audioStream = new MediaStream
      audioStream.addTrack(audioTrack)
      videoStream.addTrack(videoTrack)
      videoEl.srcObject = videoStream
      audioEl.srcObject = audioStream
      videoEl.oncanplay = () => {

      }

      const videoWidth = videoEl.videoWidth
      const videoHeight = videoEl.videoHeight
      console.log(videoWidth)
      console.log(videoHeight)
    }
  }
}
</script>
